Java的Regex套件似乎只能跑迴圈一筆筆累加符合條件的片段。
int from = 0;
int count = 0;
while(matcher.find(from)) {
count++;
from = matcher.start() + 1;
}
若用Lambda就一個陳述搞定
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Test1 {
public static void main(String[] args) throws Exception {
String str = "\n" +
"Starting copy...\n" +
"SQLState = 22001, NativeError = 0" +
"Error = [Microsoft][ODBC Driver 17 for SQL Server]String data, right truncation" +
"SQLState = 22001, NativeError = 0" +
"Error = [Microsoft][ODBC Driver 17 for SQL Server]String data, right truncation" +
"" +
"28 rows copied." +
"Network packet size (bytes): 4096" +
"Clock Time (ms.) Total : 51 Average : (549.0 rows per sec.)";
Pattern failPattern = Pattern.compile("right truncation");
Matcher failMatcher = failPattern.matcher(str);
System.out.println(Stream.iterate(0, i -> i + 1)
.filter(i -> !failMatcher.find())
.findFirst()
.get());
}
}
得到結果是2,主要是Stream.iterate(0, i -> i + 1).filter(i -> !failMatcher.find()).findFirst().get();
這個陳述,但可讀性好像不及規規矩矩的寫迴圈